<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供货商名称" prop="companyName" v-show="userRole !== 'provider'" label-width="120px">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入供货商名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['supplierorders:supplierorders:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleCreateSettlement"
            v-hasPermi="['settlement:settlement:add']"
            :disabled="!canCreateSettlement"
        >创建结算单</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderExecutionList" @selection-change="handleSelectionChange" style="margin-top: 15px">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="订单编号" fixed align="center" prop="orderNo" width="125" />
      <el-table-column label="供货商名称" align="center" prop="companyName" width="120"/>
      <!-- <el-table-column label="供货商编码" align="center" prop="supplierCode" width="120"/> 新增供货商编码列 -->
      <el-table-column label="下单时间" align="center" prop="orderTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单总金额(元)" align="right" prop="orderAmount" width="120"/>
      <el-table-column label="负责人" align="center" prop="responsiblePerson" width="100"/>
      <el-table-column label="修改人" align="center" prop="modifiedBy" width="100"/>
      <el-table-column label="修改日期" align="center" prop="modifiedDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.modifiedDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <el-tag :type="primary" disable-transitions>
            {{ scope.row.orderStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" header-align="center" prop="remarks" width="180"/>
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['supplierorders:supplierorders:detail']">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 创建结算单对话框 -->
    <el-dialog title="创建结算单" v-model="settlementOpen" width="600px" append-to-body>
      <el-form ref="settlementRef" :model="settlementForm" :rules="settlementRules" label-width="100px">
        <el-form-item label="合作方编码" prop="partnerCode">
          <el-input v-model="settlementForm.partnerCode" placeholder="请输入合作方编码" disabled />
        </el-form-item>
        <el-form-item label="订单总金额" prop="orderAmount">
          <el-input v-model="settlementForm.orderAmount" placeholder="请输入结算总金额" disabled />
        </el-form-item>   
        <!-- <el-form-item label="货币单位" prop="currencyUnit">
          <el-input v-model="settlementForm.currencyUnit" placeholder="请输入货币单位" />
        </el-form-item> -->
        <!-- <el-form-item label="结算方式" prop="settlementMethod">
          <el-input v-model="settlementForm.settlementMethod" placeholder="请输入结算方式,0为支付宝，1为微信，2为银联" />
        </el-form-item> -->
        <el-form-item label="协议编码" prop="agreementCode">
          <el-input v-model="settlementForm.agreementCode" placeholder="请输入协议编码" disabled />
        </el-form-item>
     
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="settlementForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">结算详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddSettlementDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteSettlementDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="settlementDetailList" :row-class-name="rowSettlementDetailIndex" @selection-change="handleSettlementDetailSelectionChange" ref="settlementDetailTable">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="订单编码" align="center" prop="orderCode" />
          <el-table-column label="订单金额" align="center" prop="orderAmount" />
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSettlementForm">确 定</el-button>
          <el-button @click="cancelSettlement">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="supplierorders">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { createSettlement } from "@/api/settled/record.js";
import { parseTime } from "@/utils/ruoyi.js";
import { listPurchaseExecutionOrder } from "@/api/purchase/purchaseOrder.js";
import useUserStore from '@/store/modules/user'
import { getSupplierByUsername } from "@/api/purchase/Supplier.js";
import { useRouter } from 'vue-router'; // 导入 useRouter
import { getOrderDetail } from "@/api/purchase/orderDetail.js";
import { getSupplierCodeByCompanyName } from "@/api/purchase/supplier.js";
import { getAgreementCodeByPartnerCode } from "@/api/settled/agreement.js";

const { proxy } = getCurrentInstance();
const router = useRouter(); // 初始化 router

const supplierordersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const selectedOrders = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const settlementOpen = ref(false);
const canCreateSettlement = ref(false);
const userRole = ref('');
const username = ref('');
// const companyName = ref('');


const { execution_order_status } = proxy.useDict("execution_order_status");
const orderExecutionList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    partnerCode: null,
    orderNo: "",
    companyName: "",
    supplierCode:"", // 新增 supplierCode 参数
  },
  settlementForm: {
    partnerCode: '',
    orderAmount: 0,
    settlementMethod: '',
    agreementCode: '',
    currencyUnit: '',
    taxRate: 0,
    taxAmount: 0,
    remark: ''
  },
  settlementRules: {
    agreementCode: [
      { required: true, message: "协议编码不能为空", trigger: "blur" }
    ],
  },
  settlementDetailList: [] // 初始化为空数组
});

const { queryParams, form, rules, settlementForm, settlementRules, settlementDetailList } = toRefs(data);

/** 查询供货商订单列表 */
async function getList() {
  loading.value = true;

  

  queryParams.value.pageNum = 1;
  listPurchaseExecutionOrder(queryParams.value).then(response => {
    
    orderExecutionList.value = response.rows;
    total.value = response.total;

    // 计算每个订单的总金额
    orderExecutionList.value.forEach(order => {
      calculateOrderTotalAmount(order);
    });

    loading.value = false;
  });
}

// 计算订单总金额
function calculateOrderTotalAmount(order) {
  getOrderDetail(order.orderNo).then(response => {
    const productDetails = response.data;
    const totalAmount = productDetails.reduce((sum, product) => {
      return sum + (parseFloat(product.unitPrice) * parseFloat(product.quantity));
    }, 0);
    order.orderAmount = totalAmount.toFixed(2); // 保留两位小数
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderCode: null,
    partnerCode: null,
    orderAmount: null,
    orderStatus: null,
    orderDate: null,
    creator: null,
    modifyTime: null,
    lastModifiedBy: null,
    remark: null
  };
  proxy.resetForm("supplierordersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  if(userRole.value === 'provider'){
    queryParams.value.companyName = companyName.value;
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedOrders.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;

  if (selection.length > 0) {
    const partnerCode = selection[0].partnerCode;
    canCreateSettlement.value = selection.every(order => order.partnerCode === partnerCode);
    settlementForm.value.partnerCode = partnerCode;
    settlementForm.value.orderAmount = selection.reduce((sum, order) => sum + parseFloat(order.orderAmount), 0);
  } else {
    canCreateSettlement.value = false;
    settlementForm.value.partnerCode = '';
    settlementForm.value.orderAmount = 0;
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('supplierorders/supplierorders/export', {
    ...queryParams.value
  }, `supplierorders_${new Date().getTime()}.xlsx`);
}

// 创建结算单按钮操作
async function handleCreateSettlement() {
  if (selectedOrders.value.length === 0) {
    proxy.$modal.msgWarning("请先选择订单");
    return;
  }

  // 获取第一个选中订单的供货商名称
  const firstOrder = selectedOrders.value[0];
  const companyName = firstOrder.companyName;

  try {
    // 调用接口获取供货商编码
    const response = await getSupplierCodeByCompanyName(companyName);
    console.log("接口返回数据:", response);

    if (response.code === 200) {
      // 将供货商编码赋值给 partnerCode
      settlementForm.value.partnerCode = response.msg;
    } else {
      proxy.$modal.msgError(response.msg || "获取供货商编码失败");
      return;
    }
  } catch (error) {
    console.error("获取供货商编码失败:", error);
    proxy.$modal.msgError("获取供货商编码失败");
    return;
  }

  try {
    // 调用获取协议编码的方法
    const response = await getAgreementCodeByPartnerCode(settlementForm.value.partnerCode);
    console.log("获取协议编码响应:", response); // 添加日志
    if (response.code === 200) {
      settlementForm.value.agreementCode = response.msg; // 确保 response.data.agreementCode 包含协议编码
    } else {
      proxy.$modal.msgError(response.msg || "获取协议编码失败");
      return;
    }
  } catch (error) {
    console.error("获取协议编码失败:", error);
    proxy.$modal.msgError("获取协议编码失败");
    return;
  }

  

  // 计算选中订单的总金额
  settlementForm.value.orderAmount = selectedOrders.value.reduce((sum, order) => sum + parseFloat(order.orderAmount), 0);

   // 生成结算单编码（假设后端生成，这里可以留空或生成一个临时编码）
   const settlementCode = "SETTLEMENT-" + Date.now(); // 临时编码，实际应由后端生成
  settlementForm.value.settlementCode = settlementCode;

  // 设置结算单详情列表
  settlementDetailList.value = selectedOrders.value.map((order, index) => ({
    index: index + 1,
    orderCode: order.orderNo, // 订单编码
    orderAmount: order.orderAmount, // 订单金额
    settlementCode: settlementCode // 结算单编码
  }));
  

 

  // 打开结算单对话框
  settlementOpen.value = true;
}

// 取消创建结算单
function cancelSettlement() {
  settlementOpen.value = false;
  resetSettlementForm();
}

// 重置结算单表单
function resetSettlementForm() {
  settlementForm.value = {
    partnerCode: '',
    orderAmount: 0,
    remark: ''
  };
  proxy.resetForm("settlementRef");
}

// 提交结算单表单
function submitSettlementForm() {
  proxy.$refs["settlementRef"].validate(valid => {
    if (valid) {
      // 构造提交数据
      const dataToSend = {
        ...settlementForm.value, // 结算单信息
        settlementDetailList: settlementDetailList.value // 结算明细列表
      };

      // 调用创建结算单接口
      createSettlement(dataToSend).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("结算单创建成功");
          settlementOpen.value = false; // 关闭对话框
          resetSettlementForm(); // 重置表单
          getList(); // 刷新列表
        } else {
          proxy.$modal.msgError(response.msg || "结算单创建失败");
        }
      }).catch(error => {
        proxy.$modal.msgError("结算单创建失败");
      });
    }
  });
}

// 行索引
function rowSettlementDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
  return '';
}

// 查看详情按钮操作
function handleDetail(row) {
  router.push({
    path: '/OrderDetail/index/' + row.orderNo
  });
}

getList();
</script>